package com.storeapp.ui.compator;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;

import com.storeapp.entity.domain.Item;

public class ItemTableCompator extends ViewerComparator {
	private int propertyIndex;
	private static final int DESCENDING = 1;
	private int direction = DESCENDING;

	public ItemTableCompator() {
		this.propertyIndex = 0;
		direction = DESCENDING;
	}

	public void setColumn(int column) {
		if (column == this.propertyIndex) {
			// Same column as last sort; toggle the direction
			direction = 1 - direction;
		} else {
			// New column; do an ascending sort
			this.propertyIndex = column;
			direction = DESCENDING;
		}
	}

	@Override
	public int compare(Viewer viewer, Object e1, Object e2) {
		Item item1 = (Item) e1;
		Item item2 = (Item) e2;
		int rc = 0;
		switch (propertyIndex) {
		case 0:
			rc = item1.getItemName().compareTo(item2.getItemName());
			break;
		case 1:
			rc = item1.getProvider().compareTo(item2.getProvider());
			break;
		case 2:
			if( item1.getPrice() == item2.getPrice()){
				rc = 0;
			} else {
				rc = ( item1.getPrice() >= item2.getPrice() ? 1 : -1 );
			}
			break;
		case 3:
			if( item1.getQuantity() == item2.getQuantity()){
				rc = 0;
			} else {
				rc = ( item1.getQuantity() >= item2.getQuantity() ? 1 : -1 );
			}
			break;
		case 4:
			if( item1.getDiscount() == item2.getDiscount()){
				rc = 0;
			} else {
				rc = ( item1.getDiscount() >= item2.getDiscount() ? 1 : -1 );
			}
			break;
		case 5:
			rc = item1.getGuarentee().compareTo(item2.getGuarentee());
			break;
		default:
			rc = 0;
		}
		// If descending order, flip the direction
		if (direction == DESCENDING) {
			rc = -rc;
		}
		return rc;
	}
}
